package com.qianfeng.web;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.google.gson.Gson;
import com.qianfeng.entity.Bm;
import com.qianfeng.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/getType")
public class GetType extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DruidPooledConnection connection = DruidUtil.getConnection();


        ArrayList<Bm> bms = new ArrayList<>();
        ResultSet rs =null;
        PreparedStatement ps =null;
        try {
          ps = connection.prepareStatement("select id,type,salary,imgs from bm group by type having min(salary)");
          rs = ps.executeQuery();

            while(rs.next()){
                int id = rs.getInt(1);
                String type = rs.getString(2);
                double salary = rs.getDouble(3);
                String is = rs.getString(4);
                String[] imgs = is.split(",");
                Bm bm = new Bm();
                bm.setId(id);
                bm.setType(type);
                bm.setSalary(salary);
                bm.setImgs(imgs);
                bms.add(bm);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                rs.close();
                ps.close();
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        Gson gson = new Gson();
        String s = gson.toJson(bms);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println(s);
    }
}
